<?php
  class LwaUtil {

    /**
     * Enter description here...
     *
     * @param unknown_type $variable
     * @param unknown_type $nullvalue
     * @return unknown
     */
    public static function dumpLwaVariable($variable, $nullvalue = '""') {
      if (is_null($variable)) return $nullvalue;
      if (is_array($variable)) {
        $ar = array();
        foreach ($variable as $value) {
          $ar[] = self::dumpLwaVariable($value, $nullvalue);
        }
        if (count($ar)<50) {
          return '_('.join(',', $ar).')';
        } else {
          return '['.join(',', $ar).']';
        }
      } else if (is_object($variable)) {
        $ret = ' [';
        foreach ($variable as $key=>$value) {
          $ret .= $key.'='.self::dumpLwaVariable($value, $nullvalue).',';
        }
        $count = strlen($ret)-1;
        if ($ret[$count] == ',') {
          $ret[$count] = ']';
        } else {
          $ret .= ']';
        }
        return $ret;
      } else if (is_string($variable)) {
        return str_replace("\n", "\\n", var_export($variable, 1));
      } else {
        return var_export($variable, 1);
      }
    }


  public static function arrayToDOMDocument(array $source, $rootTagName = 'root')
  {
    $document = new DOMDocument();
    $document->appendChild(self::createDOMElement($source, $rootTagName, $document));

    return $document;
  }

  /**
   * @param array $source
   * @param string $rootTagName
   * @param bool $formatOutput
   * @return string
   */
  public static function arrayToXMLString(array $source, $rootTagName = 'root', $formatOutput = true)
  {
    $document = self::arrayToDOMDocument($source, $rootTagName);
    $document->formatOutput = $formatOutput;
    return $document->saveXML();
  }

  private static function createDOMElement($source, $tagName, DOMDocument $document)
  {
    if (!is_array($source))
      return $document->createElement($tagName, $source);

    $element = $document->createElement($tagName);

    foreach ($source as $key => $value)
      if (is_string($key))
        foreach ((is_array($value) ? $value : array($value)) as $elementKey => $elementValue)
          $element->appendChild(self::createDOMElement($elementValue, $key, $document));
      else
        $element->appendChild(self::createDOMElement($value, $tagName, $document));
      
    return $element;
  }


    public static function dumpJsonXml($var) {
      if (@$_REQUEST['xml']) {
        return self::arrayToXMLString($var, 'root', false);
      } else {
        return json_encode($var);
      }
    }

  }
